package Controller;

import DAO.UserDao;
import com.alibaba.fastjson.JSON;
import entity.Return;
import entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "loginAction", value = "/loginAction")
public class loginController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        super.doGet(request, response);
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        super.doPost(request, response);
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        response.setContentType("text/html;charset=UTF-8");
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        System.out.println("Login:"+username+"........"+password);
        request.getSession().setAttribute("ISadmin","false");

        if (username.equals("admin") && password.equals("admin")){
            request.getSession().setAttribute("ISadmin","true");
            request.getRequestDispatcher("jsp/adminmainpage.jsp").forward(request,response);
        }

        UserDao userDao = new UserDao();
        User user = userDao.queryLogin(username,password);
        if (user != null) {
            String userStr = JSON.toJSONString(user);
            Return r = Return.ok().data("data",userStr);

            String returnStr = JSON.toJSONString(r);
            response.getWriter().write(returnStr);
            request.getSession().setAttribute("userid",user.getUserID());
            request.getSession().setAttribute("username",user.getUsername());
            request.getRequestDispatcher("jsp/mainpage.jsp").forward(request,response);
        } else {
//            Return r = Return.error().message("用户不存在或密码错误");
//            response.getWriter().println(r.toString());
//            request.getSession().setAttribute("Result",r);
            PrintWriter out = response.getWriter();
            out.write("Pass");
            out.flush();
            out.close();
            return;
        }
    }
}
